﻿using Admin2024.Domain.DomainService.Tool;
using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IUserService;
using Admin2024.Domain.Interface;
using Admin2024.Domain.ObjValue;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin2024.Domain.DomainService.System.UserService
{
    public class AuthenticationService : IAuthenticationService
    {
        private readonly IRepository<AppUser> _UserRep;

        private readonly IJwtService jwt;


        public AuthenticationService(IRepository<AppUser> repository, IJwtService jwt)
        {
            _UserRep = repository;
            this.jwt = jwt;
        }
        //登录
        public async Task<DomainResult<AppUser>> LoginUserAsync(string username, string password)
        {
            var user =  _UserRep.Table.FirstOrDefault(x => x.Username == username);
            if (user?.Id is not null) 
            {
                var UserI = await _UserRep.GetByIdAsync(user.Id);
                if (UserI == null)
                {
                    return DomainResult<AppUser>.Error("用户不存在");
                }
                if (user.IsDeleted == true)
                {
                    return DomainResult<AppUser>.Error("用户不存在");
                }
                var Salt = user.Salt;
                if (user.Password != PasswordHasher.HashPassword(password, Salt))
                {
                    return DomainResult<AppUser>.Error("用户或密码错误");
                }
                var appUser = new AppUser { Id = user.Id, Username = user.Username, Salt = user.Salt };
                return DomainResult<AppUser>.Success(appUser);
            }
            return DomainResult<AppUser>.Error("用户不存在");
        }
        //登出
        public Task<DomainResult<AppUser>> LogoutUserAsync()
        {
            throw new NotImplementedException();
        }
        //注册
        public async Task<DomainResult<AppUser>> RegisterUserAsync(string username, string password, string ConfirmPassword)
        {
            var user = _UserRep.Table.FirstOrDefault(w => w.Username == username);

            if(user != null)
            {
                return DomainResult<AppUser>.Error("用户名存在");
            }
            if (password != ConfirmPassword)
            {
                return DomainResult<AppUser>.Error("密码不相等");
            }

            var Id = Guid.NewGuid();
            var userD = new AppUser(Id, username, password) { Salt = PasswordHasher.GenerateSalt() };
            //密码加密
            userD.Haser();
  
            var reg = await _UserRep.CreateAsync(userD);
            return DomainResult<AppUser>.Success(reg);
        }
    }
}
